<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>一键出题 - 智慧教育考试系统</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

  <!-- 配置Tailwind自定义主题 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#165DFF',
            secondary: '#36D399',
            accent: '#FF9F43',
            neutral: '#F8FAFC',
            'neutral-dark': '#334155',
          },
          fontFamily: {
            inter: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>

  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .card-shadow {
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      }
      .nav-hover {
        @apply transition-all duration-300 hover:bg-primary/10 hover:text-primary;
      }
      .btn-primary {
        @apply bg-primary text-white px-4 py-2 rounded-lg transition-all duration-300 hover:bg-primary/90 active:bg-primary/80;
      }
      .btn-secondary {
        @apply bg-white border border-gray-200 text-neutral-dark px-4 py-2 rounded-lg transition-all duration-300 hover:bg-gray-50 active:bg-gray-100;
      }
      .btn-danger {
        @apply bg-red-50 text-red-600 border border-red-200 px-4 py-2 rounded-lg transition-all duration-300 hover:bg-red-100 active:bg-red-200;
      }
    }
    /* Vendor prefixes for compatibility */
    * {
      -webkit-user-select: text;
      user-select: text;
      -webkit-text-size-adjust: 100%;
      text-size-adjust: 100%;
    }
    /* For mask if used */
    .masked {
      -webkit-mask: url(#mask);
      mask: url(#mask);
    }
  </style>
</head>
<body class="font-inter bg-gray-50 text-neutral-dark min-h-screen flex flex-col">
  <div id="exam-name-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center hidden">
    <div class="bg-white rounded-lg p-6 w-full max-w-sm shadow-xl">
      <h3 class="text-lg font-semibold mb-4">输入试卷名称</h3>
      <input id="exam-name-input" type="text" class="w-full border border-gray-300 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary/50" placeholder="请输入试卷名称">
      <div class="flex justify-end gap-3 mt-6">
        <button id="exam-name-cancel" class="btn-secondary px-4 py-2">取消</button>
        <button id="exam-name-confirm" class="btn-primary px-4 py-2">确定</button>
      </div>
    </div>
  </div>
  <!-- 顶部导航栏 -->
  <header class="bg-white border-b border-gray-200 sticky top-0 z-30">
    <div class="container mx-auto px-4 py-3 flex items-center justify-between">
      <div class="flex items-center space-x-2">
        <i class="fa fa-graduation-cap text-primary text-2xl"></i>
        <h1 class="text-xl font-bold text-primary">智慧教育考试系统</h1>

      </div>

      <div class="flex items-center space-x-6">
        <div class="hidden md:flex items-center space-x-4">
          <button class="text-gray-500 hover:text-primary transition-colors">
            <i class="fa fa-bell-o"></i>
          </button>
          <button class="text-gray-500 hover:text-primary transition-colors">
            <i class="fa fa-cog"></i>
          </button>
        </div>

        <div class="flex items-center space-x-2">
          <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary">
            <i class="fa fa-user"></i>
          </div>
          <span class="hidden md:inline">张老师</span>
        </div>
      </div>
    </div>
  </header>

  <!-- 主内容区 -->
  <main class="flex-1 flex flex-col md:flex-row">
    <!-- 左侧导航 -->
    <aside class="w-full md:w-64 bg-white border-r border-gray-200 md:h-[calc(100vh-60px)] sticky md:sticky top-[60px] z-20">
      <!-- 角色切换 -->
      <div class="p-4 border-b border-gray-200">
        <h2 class="text-sm font-medium text-gray-500 mb-2">角色切换</h2>
        <div class="flex rounded-lg overflow-hidden border border-gray-200">
          <button id="teacher-tab" class="flex-1 py-2 px-3 bg-primary text-white text-sm font-medium">
            教师端
          </button>
          <button id="student-tab" class="flex-1 py-2 px-3 bg-white text-gray-600 text-sm font-medium hover:bg-gray-50">
            学生端
          </button>
        </div>
      </div>

      <!-- 教师导航菜单 -->
      <nav id="teacher-nav" class="p-2">
        <ul class="space-y-1">
          <li>
            <a href="/home" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-bar-chart w-5 text-center"></i>
              <span>教师控制台</span>
            </a>
          </li>
          <li>
            <a href="/Set_questions" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover text-primary bg-primary/10">
              <i class="fa fa-magic w-5 text-center"></i>
              <span>发布考试</span>
            </a>
          </li>
          <li>
            <a href="/History_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-history w-5 text-center"></i>
              <span>历史考试</span>
            </a>
          </li>
          <li>
            <a href="/Set_questions" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-magic w-5 text-center"></i>
              <span>一键出题</span>
            </a>
          </li>
          <li>
            <a href="/Question_Bank" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-book w-5 text-center"></i>
              <span>题库管理</span>
            </a>
          </li>
          <li>
            <a href="/stu_management" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-users w-5 text-center"></i>
              <span>学生管理</span>
            </a>
          </li>
          <li>
            <a href="/class_management" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-th-large w-5 text-center"></i>
              <span>班级管理</span>
            </a>
          </li>
        </ul>
      </nav>

      <!-- 学生导航菜单 (默认隐藏) -->
      <nav id="student-nav" class="p-2 hidden">
        <ul class="space-y-1">
          <li>
            <a href="/Exam_record" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-file-text-o w-5 text-center"></i>
              <span>个人考试记录</span>
            </a>
          </li>
          <li>
            <a href="/Waiting_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-clock-o w-5 text-center"></i>
              <span>待考试</span>
              <span class="ml-auto bg-accent text-white text-xs px-2 py-0.5 rounded-full">3</span>
            </a>
          </li>
          <li>
            <a href="/Mistake_question" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-exclamation-circle w-5 text-center"></i>
              <span>错题本</span>
            </a>
          </li>
        </ul>
      </nav>
    </aside>



    <div class="flex-1 p-4 md:p-6 overflow-auto">
      <!-- 新增：选择题库出题区域 -->
      <div id="bank-content" class="mb-6 hidden">
        <div class="bg-white rounded-xl p-5 card-shadow mb-6">
          <h3 class="font-bold text-lg mb-4">选择题库出题</h3>

          <!-- 题库筛选条件 -->
          <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">学科</label>
              <select class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors" aria-label="学科选择">
                <option value="">全部学科</option>
              {% for subject_type in subject_type_options %}
                <option value="{{ subject_type }}">{{ subject_type }}</option>
              {% endfor %}
              </select>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">知识点</label>
              <select class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors" aria-label="知识点选择">
                <option value="">全部知识点</option>
                {% for knowledge_type in knowledge_options %}
                <option value="{{ knowledge_type }}">{{ knowledge_type }}</option>
              {% endfor %}
              </select>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">年纪</label>
              <select class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors" aria-label="年级选择">
                <option value="">全部年级</option>
                {% for grade_type in grade_options %}
                <option value="{{ grade_type }}">{{ grade_type }}</option>
              {% endfor %}
              </select>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">题型</label>
              <select class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors" aria-label="题型选择">
                <option value="">全部题型</option>
                <option value="选择题" {% if request.args.get('type') == '选择题' %}selected{% endif %}>单选题</option>
                <option value="多选题" {% if request.args.get('type') == '多选题' %}selected{% endif %}>多选题</option>
                <option value="填空题" {% if request.args.get('type') == '填空题' %}selected{% endif %}>填空题</option>
                <option value="简答题" {% if request.args.get('type') == '简答题' %}selected{% endif %}>简答题</option>
              </select>
            </div>
          </div>
          <button class="btn-primary text-sm px-3 py-1" id="select" type="button">
                  <i class="fa fa-plus mr-1"></i> 筛选
          </button>

          <!-- 题库列表 -->
          <div class="border border-gray-200 rounded-lg overflow-hidden">
            <div class="bg-gray-50 p-3 border-b border-gray-200 flex justify-between items-center">
              <h4 class="font-medium">题目列表</h4>
              <div class="flex items-center">
                <input type="text" placeholder="搜索题目..." class="px-3 py-1 text-sm border border-gray-300 rounded-l-lg focus:outline-none focus:ring-1 focus:ring-primary">
                <button class="bg-primary text-white px-3 py-1 text-sm rounded-r-lg">
                  <i class="fa fa-search"></i>
                </button>
              </div>
            </div>

            <div class="max-h-80 overflow-y-auto">
              <!-- 题目项 -->
              {% for q in questions %}
                <div class="p-4 border-b border-gray-100 hover:bg-gray-50 transition-colors" data-id="{{ q.id }}" data-question="{{ q.title|e }}" data-type="{{ q.type|e }}" data-subject="{{ q.subject|e }}" data-grade="{{ q.grade|e }}" data-option='{{ q.option|tojson|safe }}' data-answer="{{ q.answer|e }}">
                  <div class="flex items-start">
                    <input type="checkbox" class="mt-1 mr-3 question-checkbox" id="q{{ q.id }}">
                    <label for="q{{ q.id }}" class="flex-1 cursor-pointer">
                      <div class="bg-white rounded-lg p-3 shadow-sm hover:shadow-md transition-shadow">
                        <p class="font-medium text-base mb-2">{{ q.title }}</p>
                        
                        <!-- 显示选项 -->
                        {% if q.option %}
                        <div class="mb-2">
                          <p class="text-xs text-gray-500 mb-1">选项：</p>
                          <div class="text-sm bg-gray-50 p-2 rounded">
                            {% if q.type in ['选择题', '多选题'] %}
                              {% if q.option is iterable and q.option is not string %}
                                {% for opt in q.option %}
                                  <div class="mb-1">{{ opt }}</div>
                                {% endfor %}
                              {% else %}
                                <div>{{ q.option }}</div>
                              {% endif %}
                            {% else %}
                              <div>{{ q.option }}</div>
                            {% endif %}
                          </div>
                        </div>
                        {% endif %}
                        
                        <!-- 显示答案 -->
                        <div class="mb-2">
                          <p class="text-xs text-gray-500 mb-1">答案：</p>
                          <div class="text-sm bg-green-50 p-2 rounded text-green-800">{{ q.answer }}</div>
                        </div>
                        
                        <!-- 题目标签 -->
                        <div class="flex flex-wrap gap-2 text-xs text-gray-500 mt-2">
                          <span class="bg-blue-100 text-blue-700 px-2 py-1 rounded-full"><i class="fa fa-tag mr-1"></i> {{ q.subject }}</span>
                          <span class="bg-purple-100 text-purple-700 px-2 py-1 rounded-full"><i class="fa fa-graduation-cap mr-1"></i> {{ q.grade }}年级</span>
                          <span class="bg-orange-100 text-orange-700 px-2 py-1 rounded-full"><i class="fa fa-list-alt mr-1"></i> {{ q.type }}</span>
                          {% if q.knowledge %}
                          <span class="bg-teal-100 text-teal-700 px-2 py-1 rounded-full"><i class="fa fa-lightbulb-o mr-1"></i> {{ q.knowledge }}</span>
                          {% endif %}
                          <span class="bg-yellow-100 text-yellow-700 px-2 py-1 rounded-full"><i class="fa fa-star mr-1"></i> {{ q.score }}分</span>
                        </div>
                      </div>
                    </label>
                  </div>
                </div>
              {% endfor %}
            </div>

            <!-- 分页 -->
            <div class="p-3 border-t border-gray-200 flex justify-between items-center">
              <div class="text-sm text-gray-500">
                第 {{ pagination.page }} 页，共 {{ pagination.pages }} 页，每页 {{ pagination.per_page }} 题，总 {{ pagination.total }} 题
              </div>
              <div class="flex space-x-2">
                {% if pagination.has_prev %}
                <a href="{{ url_for('create_exambp.create_exams', page=pagination.prev_num) }}" class="btn-secondary text-sm px-3 py-1">上一页</a>
                {% endif %}
                {% for page_num in pagination.iter_pages() %}
                  {% if page_num %}
                    <a href="{{ url_for('create_exambp.create_exams', page=page_num) }}" class="btn-secondary text-sm px-3 py-1 {{ 'bg-primary text-white' if page_num == pagination.page else '' }}">{{ page_num }}</a>
                  {% else %}
                    <span class="text-sm px-3 py-1">...</span>
                  {% endif %}
                {% endfor %}
                {% if pagination.has_next %}
                <a href="{{ url_for('create_exambp.create_exams', page=pagination.next_num) }}" class="btn-secondary text-sm px-3 py-1">下一页</a>
                {% endif %}
              </div>
            </div>

            <div class="p-3 border-t border-gray-200 flex justify-between items-center">
              <div class="text-sm text-gray-500">已选择 <span class="text-primary font-medium">0</span> 道题</div>
              <div class="flex space-x-2">
                <button class="btn-secondary text-sm px-3 py-1">
                  <i class="fa fa-check-square-o mr-1"></i> 全选
                </button>
                <button class="btn-primary text-sm px-3 py-1" id="add-selected">
                  <i class="fa fa-plus mr-1"></i> 添加选中题目
                </button>
              </div>
            </div>
          </div>
        </div>

      <!-- 生成的试题预览 -->
      <div class="bg-white rounded-xl p-5 card-shadow mb-6">
        <div class="flex justify-between items-center mb-4">
          <h3 class="font-bold text-lg">试题预览</h3>
          <span class="text-sm text-gray-500">点击试题可进行编辑</span>
        </div>

        <div class="space-y-6">
          <!-- 选择题预览 -->
          <div>
            <div id="preview-single-choice" class="space-y-4 pl-4 border-l-2 border-primary/20">
              <!-- 动态渲染的选中题目将在这里显示 -->
            </div>
          </div>

        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="flex flex-col sm:flex-row justify-center gap-4 mb-6">
          <!-- 生成试题按钮 -->
        <button class="btn-primary flex-1 sm:flex-none min-w-[140px] justify-center py-3" id="save_exam_btn">
          <i class="fa fa-save mr-2"></i> 保存为考试
        </button>
        <button class="btn-secondary flex-1 sm:flex-none min-w-[140px] justify-center py-3">
          <i class="fa fa-refresh mr-2"></i> 重新生成
        </button>
        <button class="btn-danger flex-1 sm:flex-none min-w-[140px] justify-center py-3" id="breakedit">
          <i class="fa fa-times mr-2"></i> 清空预览
        </button>
      </div>
    </div>
    </div>
  </main>

  <!-- 页脚 -->
  <footer class="bg-white border-t border-gray-200 py-4">
    <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
      <p> 2025 智慧教育考试系统 版权所有</p>
    </div>
  </footer>

  <div id="selected-questions-data" style="display: none;">{{ selected_questions|default([])|tojson|safe }}</div>

  <script>
    const initialSelectedQuestions = (() => {
      const dataEl = document.getElementById('selected-questions-data');
      if (!dataEl) {
        return [];
      }
      try {
        return JSON.parse(dataEl.textContent || '[]');
      } catch (error) {
        console.error('解析初始题目数据失败:', error);
        return [];
      }
    })();

    let currentSelectedQuestions = [];

    const renderSelectedQuestions = (questions) => {
      const previewContainer = document.getElementById('preview-single-choice');
      if (!previewContainer) {
        return;
      }

      const list = Array.isArray(questions) ? questions : [];
      currentSelectedQuestions = list;
      previewContainer.innerHTML = '';

      if (!list.length) {
        previewContainer.innerHTML = '<p class="text-gray-500 text-center py-4">暂无选中题目</p>';
        return;
      }

      list.forEach((item) => {
        let options = [];
        try {
          options = JSON.parse(item.option || '[]');
        } catch (error) {
          console.error('解析选项失败:', error);
          options = [];
        }

        const questionDiv = document.createElement('div');
        questionDiv.className = 'p-3 border border-gray-100 rounded-lg hover:border-primary/30 transition-colors';

        questionDiv.innerHTML = `
          <p class="font-medium mb-2">${item.question || ''}</p>
          <div class="space-y-1 ml-4">
            ${options.map((optionText, index) => `
              <div class="flex items-center">
                <input type="radio"
                       id="opt-${item.id || ''}-${index}"
                       name="question-${item.id || ''}"
                       class="mr-2"
                       value="${index}">
                <label for="opt-${item.id || ''}-${index}">${optionText || ''}</label>
              </div>
            `).join('')}
          </div>
          <div class="mt-3 text-sm text-gray-600">
            <p>正确答案：${item.answer || ''}</p>
          </div>
          <div class="mt-4 flex items-center gap-3">
            <button class="px-3 py-1 text-sm rounded bg-primary text-white hover:bg-primary/90 transition edit-question-btn" data-id="${item.id}">
              <i class="fa fa-pencil mr-1"></i> 编辑
            </button>
            <button class="px-3 py-1 text-sm rounded bg-red-500 text-white hover:bg-red-500/90 transition delete-question-btn" data-id="${item.id}">
              <i class="fa fa-trash mr-1"></i> 删除
            </button>
          </div>
        `;

        previewContainer.appendChild(questionDiv);
      });

      attachQuestionCardHandlers();
    };

    const attachQuestionCardHandlers = () => {
      const editButtons = document.querySelectorAll('.edit-question-btn');
      const deleteButtons = document.querySelectorAll('.delete-question-btn');

      editButtons.forEach((button) => {
        button.addEventListener('click', () => {
          const questionId = button.getAttribute('data-id');
          handleEditQuestion(questionId);
        });
      });

      deleteButtons.forEach((button) => {
        button.addEventListener('click', () => {
          const questionId = button.getAttribute('data-id');
          handleDeleteQuestion(questionId);
        });
      });
    };

    const handleDeleteQuestion = (questionId) => {
      if (!questionId) {
        return;
      }

      const confirmed = confirm('确定要删除该题目吗？');
      if (!confirmed) {
        return;
      }

      fetch('/delete_question', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ id: questionId }),
      })
        .then((response) => response.json())
        .then((data) => {
          if (data.status === 'success') {
            const updated = Array.isArray(data.updated_questions) ? data.updated_questions : [];
            renderSelectedQuestions(updated);
            alert(data.message);
          } else {
            alert(data.message || '删除失败，请稍后再试。');
          }
        })
        .catch((error) => {
          console.error('删除题目失败:', error);
          alert('删除失败，请稍后再试。');
        });
    };

    const handleEditQuestion = (questionId) => {
      if (!questionId) {
        return;
      }

      const targetQuestion = currentSelectedQuestions.find((item) => String(item.id) === String(questionId));
      if (!targetQuestion) {
        alert('未找到该题目，无法编辑。');
        return;
      }

      let options = [];
      try {
        options = JSON.parse(targetQuestion.option || '[]');
      } catch (error) {
        console.error('解析选项失败:', error);
        options = [];
      }

      const updatedQuestionText = prompt('请输入新的题目内容：', targetQuestion.question || '');
      if (updatedQuestionText === null) {
        return;
      }

      const updatedOptionsInput = prompt('请输入新的选项，每行一个：', options.join('\n'));
      if (updatedOptionsInput === null) {
        return;
      }

      const updatedAnswer = prompt('请输入新的答案：', targetQuestion.answer || '');
      if (updatedAnswer === null) {
        return;
      }

      const updatedOptions = updatedOptionsInput
        .split('\n')
        .map((option) => option.trim())
        .filter((option) => option.length > 0);

      if (!updatedOptions.length) {
        alert('选项不能为空。');
        return;
      }

      fetch('/update_question', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          id: questionId,
          question: updatedQuestionText,
          answer: updatedAnswer,
          options: updatedOptions,
        }),
      })
        .then((response) => response.json())
        .then((data) => {
          if (data.status === 'success' && data.updated_question) {
            currentSelectedQuestions = currentSelectedQuestions.map((item) =>
              String(item.id) === String(questionId) ? data.updated_question : item
            );
            renderSelectedQuestions(currentSelectedQuestions);
            alert(data.message);
          } else {
            alert(data.message || '编辑失败，请稍后再试。');
          }
        })
        .catch((error) => {
          console.error('编辑题目失败:', error);
          alert('编辑失败，请稍后再试。');
        });
    };

    const setupRoleSwitch = () => {
      const teacherTab = document.getElementById('teacher-tab');
      const studentTab = document.getElementById('student-tab');
      const teacherNav = document.getElementById('teacher-nav');
      const studentNav = document.getElementById('student-nav');

      if (!teacherTab || !studentTab || !teacherNav || !studentNav) {
        return;
      }

      teacherTab.addEventListener('click', () => {
        teacherTab.classList.add('bg-primary', 'text-white');
        teacherTab.classList.remove('bg-white', 'text-gray-600', 'hover:bg-gray-50');
        studentTab.classList.add('bg-white', 'text-gray-600', 'hover:bg-gray-50');
        studentTab.classList.remove('bg-primary', 'text-white');

        teacherNav.classList.remove('hidden');
        studentNav.classList.add('hidden');
      });

    };

    const setupModeSwitch = () => {
      const descMode = document.getElementById('desc-mode');
      const pdfMode = document.getElementById('pdf-mode');
      const importMode = document.getElementById('import-mode');
      const bankMode = document.getElementById('bank-mode');

      const descContent = document.getElementById('desc-content');
      const pdfContent = document.getElementById('pdf-content');
      const importContent = document.getElementById('import-content');
      const bankContent = document.getElementById('bank-content');

      if (!descMode || !pdfMode || !importMode || !bankMode) {
        return;
      }

      const resetAllModes = () => {
        [descMode, pdfMode, importMode, bankMode].forEach((mode) => {
          mode.classList.add('border-gray-200');
          mode.classList.remove('border-primary', 'bg-primary/5');
        });

        [descContent, pdfContent, importContent, bankContent].forEach((content) => {
          if (content) {
            content.classList.add('hidden');
          }
        });
      };

      descMode.addEventListener('click', () => {
        resetAllModes();
        descMode.classList.add('border-primary', 'bg-primary/5');
        descMode.classList.remove('border-gray-200');
        if (descContent) {
          descContent.classList.remove('hidden');
        }
      });

      pdfMode.addEventListener('click', () => {
        resetAllModes();
        pdfMode.classList.add('border-primary', 'bg-primary/5');
        pdfMode.classList.remove('border-gray-200');
        if (pdfContent) {
          pdfContent.classList.remove('hidden');
        }
      });

      importMode.addEventListener('click', () => {
        resetAllModes();
        importMode.classList.add('border-primary', 'bg-primary/5');
        importMode.classList.remove('border-gray-200');
        if (importContent) {
          importContent.classList.remove('hidden');
        }
      });

      bankMode.addEventListener('click', () => {
        resetAllModes();
        bankMode.classList.add('border-primary', 'bg-primary/5');
        bankMode.classList.remove('border-gray-200');
        if (bankContent) {
          bankContent.classList.remove('hidden');
        }
      });
    };

    const setupQuantityControls = () => {
      const quantityBtns = document.querySelectorAll('.quantity-btn');
      const numberInputs = document.querySelectorAll('input[type="number"]');
      const totalQuestionsEl = document.getElementById('total-questions');

      if (!totalQuestionsEl) {
        return;
      }

      const calculateTotal = () => {
        const single = parseInt(document.getElementById('single-choice')?.value, 10) || 0;
        const multiple = parseInt(document.getElementById('multiple-choice')?.value, 10) || 0;
        const trueFalse = parseInt(document.getElementById('true-false')?.value, 10) || 0;
        const fillBlank = parseInt(document.getElementById('fill-blank')?.value, 10) || 0;
        const shortAnswer = parseInt(document.getElementById('short-answer')?.value, 10) || 0;

        totalQuestionsEl.textContent = single + multiple + trueFalse + fillBlank + shortAnswer;
      };

      quantityBtns.forEach((btn) => {
        btn.addEventListener('click', () => {
          const targetId = btn.getAttribute('data-target');
          const action = btn.getAttribute('data-action');
          const inputEl = targetId ? document.getElementById(targetId) : null;
          if (!inputEl) {
            return;
          }

          let value = parseInt(inputEl.value, 10) || 0;
          const min = parseInt(inputEl.min, 10) || 0;
          const max = parseInt(inputEl.max, 10) || 100;

          if (action === 'increase' && value < max) {
            value += 1;
          } else if (action === 'decrease' && value > min) {
            value -= 1;
          }

          inputEl.value = value;
          calculateTotal();
        });
      });

      numberInputs.forEach((input) => {
        input.addEventListener('change', () => {
          const min = parseInt(input.min, 10) || 0;
          const max = parseInt(input.max, 10) || 100;
          let value = parseInt(input.value, 10) || 0;
          value = Math.min(Math.max(value, min), max);
          input.value = value;
          calculateTotal();
        });
      });

      calculateTotal();
    };

    const setupPdfUpload = () => {
      const pdfUpload = document.getElementById('pdf-upload');
      const pdfPreview = document.getElementById('pdf-preview');
      const pdfFilename = document.getElementById('pdf-filename');
      const removePdf = document.getElementById('remove-pdf');

      if (!pdfUpload || !pdfPreview || !pdfFilename || !removePdf) {
        return;
      }

      pdfUpload.addEventListener('change', (event) => {
        const [file] = event.target.files || [];
        if (file) {
          pdfFilename.textContent = file.name;
          pdfPreview.classList.remove('hidden');
        }
      });

      removePdf.addEventListener('click', () => {
        pdfUpload.value = '';
        pdfPreview.classList.add('hidden');
      });
    };

    const setupExamImport = () => {
      const examUpload = document.getElementById('exam-upload');
      const examPreview = document.getElementById('exam-preview');
      const examFilename = document.getElementById('exam-filename');
      const removeExam = document.getElementById('remove-exam');

      if (!examUpload || !examPreview || !examFilename || !removeExam) {
        return;
      }

      examUpload.addEventListener('change', (event) => {
        const [file] = event.target.files || [];
        if (file) {
          examFilename.textContent = file.name;
          examPreview.classList.remove('hidden');
        }
      });

      removeExam.addEventListener('click', () => {
        examUpload.value = '';
        examPreview.classList.add('hidden');
      });

      document.querySelectorAll('.space-y-2 .text-primary').forEach((btn) => {
        btn.addEventListener('click', (event) => {
          event.stopPropagation();
          const filenameEl = btn.closest('div')?.querySelector('p');
          if (filenameEl) {
            examFilename.textContent = filenameEl.textContent;
            examPreview.classList.remove('hidden');
          }
        });
      });
    };

    const setupQuestionBank = () => {
      // 预留题库相关交互逻辑
    };

    const setupaddpreview = () => {
      const selectButton = document.getElementById('add-selected');
      if (!selectButton) {
        return;
      }

      selectButton.addEventListener('click', () => {
        const selectedCheckboxes = document.querySelectorAll('.question-checkbox:checked');
        if (!selectedCheckboxes.length) {
          alert('请先选择题目！');
          return;
        }

        const selectedIds = Array.from(selectedCheckboxes).map((checkbox) => {
          const questionDiv = checkbox.closest('div[data-id]');
          return questionDiv ? questionDiv.getAttribute('data-id') : null;
        }).filter((id) => id !== null);

        fetch('/select', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            option: 'add',
            selected_ids: selectedIds,
          }),
        })
          .then((response) => response.json())
          .then((data) => {
            if (data.status === 'success') {
              renderSelectedQuestions(data.added_questions);
              alert(data.message);
            } else {
              alert(data.message || '添加失败，请重试。');
            }
          })
          .catch((error) => {
            console.error('提交失败:', error);
            alert('提交失败，请重试。');
          });
      });
    };

    const setupSelectFilter = () => {
      const selectButton = document.getElementById('select');
      if (!selectButton) {
        return;
      }

      selectButton.addEventListener('click', () => {
        const selects = document.querySelectorAll('#bank-content select');
        if (!selects.length) {
          return;
        }

        const subject = selects[0].value;
        const topic = selects[1].value;
        const grade = selects[2].value;
        const type = selects[3].value;

        window.location.href = `/select?subject=${encodeURIComponent(subject)}&topic=${encodeURIComponent(topic)}&grade=${encodeURIComponent(grade)}&type=${encodeURIComponent(type)}&option=${encodeURIComponent('select')}`;
      });
    };
    const setupCancelButton = () => {
      const cancelButton = document.getElementById('breakedit');
      if (!cancelButton) {
        return;
      }

      cancelButton.addEventListener('click', () => {
        const isConfirmed = confirm('确定要清空所有已选择的题目吗？');
        if (!isConfirmed) {
          return;
        }

        fetch('/clear_session', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
        })
          .then((response) => response.json())
          .then((data) => {
            if (data.status === 'success') {
              renderSelectedQuestions([]);
              alert(data.message);
            } else {
              alert('清空失败: ' + (data.message || '请稍后重试'));
            }
          })
          .catch((error) => {
            console.error('清空请求失败:', error);
            alert('请求失败，请重试。');
          });
      });
    };

    const setupGenerateButton = () => {
      const generateBtn = document.getElementById('generate-btn');
      if (!generateBtn) {
        return;
      }

      generateBtn.addEventListener('click', () => {
        generateBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 生成中...';
        generateBtn.disabled = true;

        setTimeout(() => {
          generateBtn.innerHTML = '<i class="fa fa-magic mr-2"></i> 生成试题';
          generateBtn.disabled = false;

          alert('试题生成成功！');

          const previewSection = document.querySelector('.bg-white.rounded-xl.p-5.card-shadow.mb-6:nth-last-of-type(2)');
          if (previewSection) {
            previewSection.scrollIntoView({ behavior: 'smooth' });
          }
        }, 1500);
      });
    };
    const save_as_exam = () => {
      const save_exam_btn = document.getElementById('save_exam_btn');
      const modal = document.getElementById('exam-name-modal');
      const input = document.getElementById('exam-name-input');
      const confirmBtn = document.getElementById('exam-name-confirm');
      const cancelBtn = document.getElementById('exam-name-cancel');

      if (!save_exam_btn || !modal || !input || !confirmBtn || !cancelBtn) {
        return;
      }

      const closeModal = () => {
        modal.classList.add('hidden');
        input.value = '';
      };

      save_exam_btn.addEventListener('click', () => {
        modal.classList.remove('hidden');
        input.focus();
      });

      cancelBtn.addEventListener('click', () => {
        closeModal();
      });

      confirmBtn.addEventListener('click', () => {
        const name = input.value.trim();
        if (!name) {
          alert('请先输入试卷名称');
          return;
        }

        window.location.href = `/save_as_exam?name=${encodeURIComponent(name)}`;
        closeModal();
      });
    };

    document.addEventListener('DOMContentLoaded', () => {
      setupRoleSwitch();
      setupModeSwitch();
      setupQuantityControls();
      setupPdfUpload();
      setupExamImport();
      setupQuestionBank();
      setupSelectFilter();
      setupGenerateButton();
      setupaddpreview();
      setupCancelButton();
      save_as_exam();

      const urlParams = new URLSearchParams(window.location.search);
      const status = urlParams.get('status');
      if (status === 'saved') {
        alert('试卷生成成功！');
        renderSelectedQuestions([]);
      } else {
        renderSelectedQuestions(initialSelectedQuestions);
        if (status === 'duplicate_name') {
          alert('试卷名称已存在，请更换名称后重试。');
        } else if (status === 'missing_name') {
          alert('未提供试卷名称，请重新保存并输入名称。');
        } else if (status === 'duplicate_questions') {
          alert('选中的题目均已存在，未添加新的题目。');
        } else if (status === 'empty_selection') {
          alert('当前没有选中的题目，请先选择题目。');
        }
      }

      if (status) {
        history.replaceState(null, '', window.location.pathname);
      }

      if (window.location.pathname === '/create_exams' || window.location.pathname === '/select') {
        const bankMode = document.getElementById('bank-mode');
        const bankContent = document.getElementById('bank-content');
        const otherModes = [
          document.getElementById('desc-mode'),
          document.getElementById('pdf-mode'),
          document.getElementById('import-mode'),
        ];
        const otherContents = [
          document.getElementById('desc-content'),
          document.getElementById('pdf-content'),
          document.getElementById('import-content'),
        ];

        otherModes.forEach((mode) => {
          if (mode) {
            mode.classList.add('border-gray-200');
            mode.classList.remove('border-primary', 'bg-primary/5');
          }
        });

        otherContents.forEach((content) => {
          if (content) {
            content.classList.add('hidden');
          }
        });

        if (bankMode) {
          bankMode.classList.add('border-primary', 'bg-primary/5');
          bankMode.classList.remove('border-gray-200');
        }

        if (bankContent) {
          bankContent.classList.remove('hidden');
        }
      }
    });

  </script>
</body>
</html>